import tkinter as tk
from tkinter import ttk, messagebox
import sys
import csvutil
import dictutil
import fileutil
import docutil
import excelutil


class RedirectText:
    def __init__(self, text_widget):
        self.text_widget = text_widget

    def write(self, string):
        self.text_widget.config(state='normal')  # 设为可写状态
        self.text_widget.insert(tk.END, string)
        self.text_widget.see(tk.END)  # 自动滚动到底部
        self.text_widget.config(state='disabled')  # 设为只读状态

    def flush(self):
        pass


def submit():
    try:
        input_data = {key: entries[key].get() for key in entries}
        print("提交的数据：")
        print(input_data)
        handle_input_data(input_data)
        messagebox.showinfo("成功", "数据提交并处理成功！")
    except Exception as e:
        print("处理过程中出现错误：", e)
        messagebox.showerror("失败", "数据处理错误，请检查日志。")


def handle_input_data(data):
    """
    占位函数，处理提交的数据
    :param data:
    :return:
    """
    data = dictutil.add_braces_to_keys(data)
    print("处理数据：", data)
    source_dir = 'source'
    target_dir = 'target'
    # 复制source下的其所有文件到target目录，如果文件存在则替换
    fileutil.copy_word_excel_files(source_dir, target_dir)
    # 重命名target目录下所有文件名，替换原文件名中的‘+++++’部分为输入的字符串，作为新名称，不匹配的不替换。
    # 例如：target目录下存在文件名为‘小额项目审批表-+++++项目.docx’，函数的参数为('target','+++++','辽宁石油化工')替换后结果为‘小额项目审批表-辽宁石油化工项目.docx’
    project_name = data.get('${项目名称}')
    fileutil.rename_files(target_dir, '+++++', project_name)
    # 获取target目录下所有文件名，并根据excel和word做分类到2个列表，不在这两类的文件都舍弃掉
    word_files, excel_files = fileutil.get_word_excel_files(target_dir)
    # 分别填充docx、excel
    for f in word_files:
        docutil.fix(target_dir + '/' + f, data)
        print('成功生成Word' + f)
    for f in excel_files:
        excelutil.fix(target_dir + '/' + f, data)
        print('成功生成Excel' + f)
    # 设定默认内容
    # 整理内容
    # 打包
    # 核对调整

    # print("处理数据：", data)


# 创建主窗口
root = tk.Tk()
root.title("文档一键填写程序")
root.geometry("800x600")

# 读取CSV文件并转换为字典
file_path = 'conf/field.csv'
data_dict = csvutil.read_csv_to_dict(file_path)

# 创建一个滚动条
main_frame = tk.Frame(root)
main_frame.pack(fill=tk.BOTH, expand=True)

canvas = tk.Canvas(main_frame)
scrollbar = tk.Scrollbar(main_frame, orient="vertical", command=canvas.yview)
scrollable_frame = tk.Frame(canvas)

scrollable_frame.bind(
    "<Configure>",
    lambda e: canvas.configure(
        scrollregion=canvas.bbox("all")
    )
)

canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)

scrollbar.pack(side="right", fill="y")
canvas.pack(side="left", fill="both", expand=True)

# 根据字典动态创建标签和输入框
entries = {}
for i, (key, value) in enumerate(data_dict.items()):
    label = tk.Label(scrollable_frame, text=key)
    label.grid(row=i, column=0, padx=10, pady=5, sticky='e')

    entry_width = max(30, len(value) + 10)  # 输入框宽度
    entry = tk.Entry(scrollable_frame, width=entry_width)
    entry.grid(row=i, column=1, padx=10, pady=5)
    entry.insert(0, value)

    entries[key] = entry

# 创建提交按钮
submit_button = tk.Button(scrollable_frame, text="提交", command=submit)
submit_button.grid(row=len(data_dict), columnspan=2, pady=20)

# 创建日志输出框
log_label = tk.Label(scrollable_frame, text="日志输出：")
log_label.grid(row=len(data_dict) + 1, column=0, padx=10, pady=5, sticky='e')

log_text = tk.Text(scrollable_frame, wrap='word', height=10, state='disabled')
log_text.grid(row=len(data_dict) + 1, column=1, padx=10, pady=5, sticky='w')

# 将print输出重定向到日志输出框
redirect_text = RedirectText(log_text)
sys.stdout = redirect_text
sys.stderr = redirect_text

# 运行主循环
root.mainloop()

# if __name__ == '__main__':
#     print("hello")
